import os,shutil
import fun_1_1, fun_3_4
import mysql.connector,requests

def get_all_files(directory):
    values = []
    for root, dirs, files in os.walk(directory):
        for file in files:

            values.append(file)
    return values

def file_download(url,pic,path):
    response = requests.get(url)
    if response.status_code == 200:
        image_content = response.content
        save_path = path+'/'+pic
        with open(save_path, 'wb') as file:
            file.write(image_content)
            return True
    else:
        return False

dir='D:/Desk/半托图片/0321/男装/原图'
files=sorted(get_all_files(dir))

datas={}
for file in files:
    o_s=file.split('_')[2]+'&'+file.split('_')[1]
    if o_s not in datas.keys():
        datas.update({o_s:[]})
    datas[o_s].append(file)

# print(datas)
mydb = mysql.connector.connect(host="43.161.240.94",user="hcecpod_com",passwd="Xcd9sMZ9DMBBkbMf",database="hcecpod_com")
mycursor = mydb.cursor()
for key, value in datas.items():
    if len(value)==3:
        target_dir=os.path.join(os.path.dirname(dir),'完成',key.split('#')[1],key.split('&')[0],key.split('#')[1])
        if not os.path.exists(target_dir):
            os.makedirs(target_dir)
        path_img=os.path.join(dir,value[0])
        path_result=os.path.join(target_dir,'1.jpg')
        try:
            fun_1_1.convert_pic(path_img,path_result)
            print("✅ 方图完成")
        except:
            print("❌ 方图失败")
        num=2
        for v in value:
            path_img=os.path.join(dir,v)
            path_result=os.path.join(target_dir,str(num)+'.jpg')
            num+=1
            try:
                fun_3_4.convert_pic(path_img,path_result)
                print("✅ 3*4完成")
            except:
                print("❌ 3*4失败")
        style_name=key.split('&')[1]
        mycursor.execute("select pic from data_pingpu where style_name ='"+style_name+"' and sort='细节'")
        myresult2=mycursor.fetchall()
        if(myresult2):
            temp_num=5
            for y in myresult2:
                if temp_num>6:
                    continue
                url2="https://hcecpod-1343049753.cos.accelerate.myqcloud.com/pingpu/"+y[0]
                temp_name=str(temp_num)+'.'+y[0].split('.')[-1]
                if(file_download(url2,temp_name,target_dir)):
                    print("✅ 细节下载完成")
                else:
                    print("❌ 细节下载失败")
                temp_num+=1
    else:
        target_dir=os.path.join(os.path.dirname(dir),'错误')
        if not os.path.exists(target_dir):
            os.makedirs(target_dir)
        for v in value:
            path_img=os.path.join(dir,v)
            path_result=os.path.join(target_dir,v)
            try:
                shutil.copy(path_img,path_result)
                print("✅ 复制完成")
            except:
                print("❌ 复制失败")

